package com.weixin.engine.daily;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * todo
 *
 * @author wangchunhui
 * @date 2024/4/16 15:30
 */
public class CountDownLatchTest {

    public static void main(String[] args) throws IOException, InterruptedException {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                8,
                10,
                100,
                TimeUnit.MICROSECONDS,
                new ArrayBlockingQueue<>(200));

        CountDownLatch countDownLatch = new CountDownLatch(3);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            int finalI = i;
            executor.execute(() -> {
                String str = getStr(finalI);
                list.add(str);
                countDownLatch.countDown();
                System.out.println(finalI + "执行完了");
            });
        }
        countDownLatch.await();
        System.out.println(list);
    }

    private static String getStr(int finalI) {
        try {
            long times = Math.round(Math.random() * 3000);
            System.out.println(finalI + "休息了" + times + "秒");
            Thread.sleep(times);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "111";
    }
}
